//
//  Sqlite4Cocoa2dxAppController.mm
//  Sqlite4Cocoa2dx
//
//  Created by yanglishuan on 13-9-4.
//  Copyright __MyCompanyName__ 2013年. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "AppController.h"
#import "cocos2d.h"
#import "EAGLView.h"
#import "AppDelegate.h"

#import "RootViewController.h"
#import "Sqlite3Utils.h"

@implementation AppController

@synthesize window;
@synthesize viewController;

#pragma mark -
#pragma mark Application lifecycle

// cocos2d application instance
static AppDelegate s_sharedApplication;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // 测试 Sqlite3Utils
    // 版本说明：beta1.0 , 目前不支持保存图片等2进制数据
    // 1. 把数据库导入到documents下
    // 提示：Sqlite3Utils不负责把数据库文件导入到documents下
    const char *dbName = "person";
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *db_source_path = [[NSBundle mainBundle] pathForResource:[NSString stringWithUTF8String:dbName] ofType:@"db"];
    NSString *doc_path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *db_des_path = [doc_path stringByAppendingFormat:@"/%@.db", [NSString stringWithUTF8String:dbName]];
    if (![fileManager fileExistsAtPath:db_des_path]) {
        BOOL rc = [fileManager copyItemAtPath:db_source_path toPath:db_des_path error:nil];
        printf("\n---------------------\n数据库文件从%s复制到%s%s\n---------------------\n", [db_source_path cStringUsingEncoding:NSUTF8StringEncoding], [db_des_path cStringUsingEncoding:NSUTF8StringEncoding], rc ? "成功": "失败");
    } else {
        printf("========= 数据库文件已经存在 =========\n");
    }
    
    // 2. 初始化Sqlite3Utils类
    Sqlite3Utils sqlite3Utils = Sqlite3Utils([db_des_path cStringUsingEncoding:NSUTF8StringEncoding]/* 这里填写数据库的路径 */);
    
    // 3. 打开数据库
    int rc = sqlite3Utils.open_sqlite();
    if (rc == SQLITE_OK) {
        printf("====== 数据库打开成功!\n");
    }else {
        printf("====== 数据库打开失败\n");
        sqlite3Utils.close_sqlite();
    }
    
    // 4. 增删改查操作
    // 4.1 查找
    const char *tableName = "student";
    
    // 重要提示：增删改查操作的条件，如果为字符串，则格式必须为| name='yls' |；
    // 如果为数据如integer或float格式，格式为| personid=6 |；
//    const char *condition = "name='yls'";
    const char *condition = "";
//    const char *condition = "personid=6";
//    const char *order = "score";
    const char *order = "";
    bool asc = true;
    
    cocos2d::CCArray *result = sqlite3Utils.results(
            tableName, /* 这里填写要查找的表名 */
            condition, /* 这里填写查找的条件，无条件填写空字符串或NULL */
            order,     /* 这里填写排序的条件，无条件填写空字符串或NULL */
            asc        /* 升序为true，降序为false,当order不为空时有效 */
            );
    
    // 打印结果
    for (int i = 0; i < result->count(); i++) {
        cocos2d::CCDictionary *dict = (cocos2d::CCDictionary *)result->objectAtIndex(i);
        cocos2d::CCInteger *p_id = (cocos2d::CCInteger *)dict->objectForKey("personid");
        cocos2d::CCString *p_name = (cocos2d::CCString *)dict->objectForKey("name");
        cocos2d::CCString *p_image = (cocos2d::CCString *)dict->objectForKey("image");
        cocos2d::CCFloat *p_score = (cocos2d::CCFloat *)dict->objectForKey("score");
        
        std::cout << "id = " << p_id->getValue() << " name = " << p_name->getCString() << " score = " << p_score->getValue();
        std::cout << " image = " << p_image->getCString() << std::endl;
    }
    
    // 4.2 插入
    cocos2d::CCDictionary *data = cocos2d::CCDictionary::create();
    cocos2d::CCString *name = cocos2d::CCString::createWithFormat("yls");
    data->setObject(name, "name");
    cocos2d::CCFloat *score = cocos2d::CCFloat::create(82.5);
    data->setObject(score, "score");
    
    sqlite3Utils.insert(tableName,  /* 这里填写要查找的表名 */
                        data        /* 要插入的数据 */
                        );
    
    // 4.3 修改
    cocos2d::CCDictionary *updateData = cocos2d::CCDictionary::create();
    cocos2d::CCString *updateName = cocos2d::CCString::createWithFormat("yang");
    updateData->setObject(updateName, "name");
    
    const char *updateCondition = "personid=3";
    sqlite3Utils.update(tableName,      /* 这里填写要查找的表名 */
                        updateData,     /* 要更新的数据 */
                        updateCondition /* 修改数据条件，必须填写 */
                        );
    
    // 4.4 删除
    const char *removeCondition = "personid=4";
    sqlite3Utils.remove(tableName,      /* 这里填写要查找的表名 */
                        removeCondition /* 删除条件，必须填写 */
                        );
    
    // 5. 关闭数据库
    sqlite3Utils.close_sqlite();
    
    // Override point for customization after application launch.

    // Add the view controller's view to the window and display.
    window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
    EAGLView *__glView = [EAGLView viewWithFrame: [window bounds]
                                     pixelFormat: kEAGLColorFormatRGBA8
                                     depthFormat: GL_DEPTH_COMPONENT16
                              preserveBackbuffer: NO
                                      sharegroup: nil
                                   multiSampling: NO
                                 numberOfSamples:0 ];

    // Use RootViewController manage EAGLView
    viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil];
    viewController.wantsFullScreenLayout = YES;
    viewController.view = __glView;

    // Set RootViewController to window
    if ( [[UIDevice currentDevice].systemVersion floatValue] < 6.0)
    {
        // warning: addSubView doesn't work on iOS6
        [window addSubview: viewController.view];
    }
    else
    {
        // use this method on ios6
        [window setRootViewController:viewController];
    }
    
    [window makeKeyAndVisible];

    [[UIApplication sharedApplication] setStatusBarHidden: YES];

    cocos2d::CCApplication::sharedApplication()->run();
    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
    cocos2d::CCDirector::sharedDirector()->pause();
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
    cocos2d::CCDirector::sharedDirector()->resume();
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
     If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
     */
    cocos2d::CCApplication::sharedApplication()->applicationDidEnterBackground();
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    /*
     Called as part of  transition from the background to the inactive state: here you can undo many of the changes made on entering the background.
     */
    cocos2d::CCApplication::sharedApplication()->applicationWillEnterForeground();
}

- (void)applicationWillTerminate:(UIApplication *)application {
    /*
     Called when the application is about to terminate.
     See also applicationDidEnterBackground:.
     */
}


#pragma mark -
#pragma mark Memory management

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
    /*
     Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.
     */
     cocos2d::CCDirector::sharedDirector()->purgeCachedData();
}


- (void)dealloc {
    [super dealloc];
}


@end

